/**
 * @file
 * @auth zhangyanbo
 * @date 2016/12/15
 */

import Vue from 'vue';
import bigdecimal from "bigdecimal";

import tpl from './tpl.html';
import commonService from '../../../common/commonService';
import lib from '../../../common/lib';
import format from '../../../common/format';
import util from '../../../common/util';
import filter from '../../../../grsc-base/util/filter';
import Loading from '../../../../grsc-base/component/Loading.vue';
import NoData from '../../../../grsc-base/component/NoData.vue'
import MathTool from '../../../../grsc-base/util/mathtool';

const PAN_TYPE_NORMAL = 1;
const PAN_TYPE_BUY = 2;
const PAN_TYPE_SELL = 3;

const HEIGHT_THEAD = 72;
const HEIGHT_PRICE = 36;
const HEIGHT_ROW = 20;

window.bigdecimal = bigdecimal;

export default Vue.extend({
    name: 'MarketBuySell',
    template: tpl,
    components: {
        loading:Loading,
        NoData
    },
    data() {
        return {
            PAN_TYPE_NORMAL,
            PAN_TYPE_BUY,
            PAN_TYPE_SELL,
            panType: PAN_TYPE_NORMAL,

            list_buy: [],
            list_sell: [],
            isLoading: true,

            currentPrice: '--',
            lastPrice: '--',

            $domBuy: null,
            $domSell: null,
            $domSellBox: null,

            hasFirstRender: false,
            oldListBuy: [],
            oldListSell: [],

            list_buy_disp: [],

            list_sell_disp: [],
        }
    },
    props:{
        wsSymbol:{
            type: String,
            default: 'USD_GOP'
        },
        tradeType: {
            type: String,
            default: 'ETH'
        },
        height: {
            type: Number,
            default: ''
        }
    },
    computed: {

    },
    watch: {
        height(newVal, oldVal) {
            this._setPanHeight();
        }
    },
    created() {
        this._loopTrade();
        this._loopInfo();

        $(document).off('$$pan.BuySellPan').on('$$pan.BuySellPan', () => {
            this._loopTradeOnce();
        });
    },
    mounted() {
        this.$domBuy = $(this.$refs.priceBuy);
        this.$domSell = $(this.$refs.priceSell);
        this.$domSellBox = $(this.$refs.priceSellBox);
    },

    methods: {

        /**
         *
         * @private
         */
        _resetFlexZero($dom) {
            $dom.css({
                '-webkit-box-flex': '0',
                '-ms-flex': '0',
                'flex': '0 0 0',
                'height': '0'
            });
        },

        _addSellBoxAnimate() {
            this.$domSellBox.addClass('sell-box--animate');
        },

        _setPanHeight() {
            // console.log('current height is: ' + this.height);
            // if (this.hasFirstRender === true) {
            //
            // }

            let h = this.height - HEIGHT_THEAD - HEIGHT_PRICE;

            if (this.panType === PAN_TYPE_BUY) {
                this._resetFlexZero(this.$domSell);
                setHeight(this.$domBuy, h);
            } else if (this.panType === PAN_TYPE_SELL) {
                this._resetFlexZero(this.$domBuy);

                // 将sellbox设置为，内容高度和盘高度的最大者
                this.$domSellBox.height(Math.max(this.list_sell.length * HEIGHT_ROW, h));

                setHeight(this.$domSell, h);
            } else {    // 买卖盘
                let half = h / 2;
                setHeight(this.$domBuy, half);
                setHeight(this.$domSell, half);
                this._setSellScroll(this.list_sell.length, true);

                // this.$domSellBox.height(h);
            }

            function setHeight($dom, h) {
                $dom.css({
                    '-webkit-box-flex': '1 0 ' + h + 'px',
                    '-ms-flex': '1 0 ' + h + 'px',
                    'flex': '1 0 ' + h + 'px',
                    'height': h + 'px'
                });
            }
        },
        _setSellScroll(listLen, isSetScroll) {
            let heightDomSell = (this.height - HEIGHT_THEAD - HEIGHT_PRICE) / 2;
            let h = listLen * HEIGHT_ROW;
            // console.log('The heightDomSell is :' + heightDomSell);
            // console.log('The content height is :' + h);

            // 内容高度 > 盘高度
            if (h > heightDomSell) {
                // console.log('The scroll height is :' + h);
                this.$domSellBox.height(h);
                if (isSetScroll === true) {
                    this.$domSell.scrollTop(h);
                }
            } else {
                this.$domSellBox.height(h);
            }

        },

        _getFinalItem(prevArr) {
            let that = this;

            if($.isEmptyObject(prevArr)){
                return [];
            }

            if (prevArr.length > 50) {
                prevArr = prevArr.slice(0, 50);
            }

            let max = _.maxBy(prevArr,1)[1];

            let newArr_obj = [];
            prevArr.forEach(function (value,index) {
                let width = value[1]/max * 100 +'%';
                if(width<'1.068%'){
                    width= '3px';
                }

                let total;
                if (that.$$symbol === 'ACT_AAC') {
                    total = new BigNumber(value[0]).mul(value[1]).mul(100000000).floor().div(100000000);
                    total = format.formatZeroSuffix(total, that.$$coinPrecision);
                }else{
                    total = filter.floorFix(MathTool.multiplication(value[0], value[1], that.$$coinPrecision), that.$$coinPrecision)
                }


                newArr_obj.push({
                    "price": filter.floorFixPrice(new bigdecimal.BigDecimal('' + value[0]).toPlainString(), that.$$coinPrecision),
                    "count": filter.floorFixPrice(value[1], that.$$amountPrecision),
                    "total": total,
                    "width": width,
                    isAdd: false,
                    isDel: false,
                    isUpdate: false
                })
            });
            return newArr_obj;
        },
        _compose(cur, old, type, cbfn){

            let curArr = cur.concat([]);    
            let oldArr = old.concat([]);
            curArr.forEach((item)=>{
                item.isDel = false;
                item.isAdd = false;
                item.isUpdate = false;
                item.price = parseFloat(item.price);
            });

            oldArr.forEach((item)=>{
                item.isDel = false;
                item.isAdd = false;
                item.isUpdate = false;
            });

            let mergeArr = [];  // 用于显示的
            cbfn && cbfn(curArr)
            
            if (!old.length){
                return curArr;
            }

             

            if(type === 'buy'){
                // console.log('cur',cur);
                // console.log('old',old);
                let i=0; let j=0;
                while(i<oldArr.length || j<curArr.length){
                    if(!oldArr[i]){
                        curArr[j].isAdd = true;
                        mergeArr.push(curArr[j]);
                        j+=1;

                    }else if(!curArr[j]){
                        oldArr[i].isDel = true;
                        mergeArr.push(oldArr[i]);
                        i+=1;
                    }else if(oldArr[i].price == curArr[j].price && oldArr[i].count == curArr[j].count){
                        mergeArr.push(curArr[j]);
                        i+=1;
                        j+=1;

                    // 新旧数据 价格相同 数量不同  更新操作
                    } else if(oldArr[i].price == curArr[j].price && oldArr[i].count != curArr[j].count){
                        curArr[j].isUpdate = true;
                        mergeArr.push(curArr[j]);
                        
                        i+=1;
                        j+=1;

                    // 旧数据 比 新数据 价格低 
                    }else if(oldArr[i].price < curArr[j].price){
                        curArr[j].isAdd = true;
                        mergeArr.push(curArr[j]);
                        j+=1;
                    // 旧 比  新  高
                    }else if(oldArr[i].price > curArr[j].price){
                        oldArr[i].isDel = true;
                        mergeArr.push(oldArr[i]);
                        i+=1;
                    }
                }
            }else if(type === 'sell'){
                // console.log('cur');
                // console.log('old');
                let i=0; let j=0;
                while(i<oldArr.length || j<curArr.length){
                    if(!oldArr[i]){

                        curArr[j].isAdd = true;
                        mergeArr.push(curArr[j]);
                        j+=1;

                    }else if(!curArr[j]){

                        oldArr[i].isDel = true;
                        mergeArr.push(oldArr[i]);
                        i+=1;

                    }else if(oldArr[i].price == curArr[j].price && oldArr[i].count == curArr[j].count){
                        mergeArr.push(curArr[j]);
                        i+=1;
                        j+=1;

                    // 新旧数据 价格相同 数量不同  更新操作
                    } else if(oldArr[i].price == curArr[j].price && oldArr[i].count != curArr[j].count){            
                        curArr[j].isUpdate = true;
                        mergeArr.push(curArr[j]);
                        
                        i+=1;
                        j+=1;

                    // 旧数据 比 新数据 价格低 
                    
                    }else if(oldArr[i].price > curArr[j].price){
                       
                        curArr[j].isAdd = true;
                        mergeArr.push(curArr[j]);
                        j+=1;
                    // 旧 比  新  高
                    }else if(oldArr[i].price < curArr[j].price){
                       
                        oldArr[i].isDel = true;
                        mergeArr.push(oldArr[i]);
                        i+=1;
                    }

                }
                // console.log('mergeArr');
                // log(mergeArr);
            }
            
            return mergeArr;
        },

        _doResult(rep) {
            let that = this;
            this.isLoading = false;

            if (rep.sell && ($.isEmptyObject(rep.sell) === true || rep.sell === '[]')) {
                this.list_sell = [];
                this.$domSellBox.hide();
            } else {
                this.$domSellBox.show();
            }


            let list_buy = this._getFinalItem(rep["buy"]);
            let list_sell = this._getFinalItem(rep["sell"]);
            // 向调用者提供买1和卖1
            // if (this.hasDispatched === false) {
            //     this.onRequested((list_buy.length > 0 && list_buy[0].price), (list_sell.length > 0 && list_sell[0].price));
            //     this.hasDispatched = true;
            // }

            // 向调用者提供买1和卖1
            if (this.hasDispatched === false) {
                this.onRequested(
                    (list_buy.length > 0 && list_buy[0].price),
                    (list_sell.length > 0 && list_sell[0].price)
                );
                this.hasDispatched = true;
            }

            // 标注价格深浅
            setPriceText(list_buy, that.$$highlightNo, 'buy');
            setPriceText(list_sell, that.$$highlightNo, 'sell');

            if (this.hasFirstRender === false) {
                this._setSellScroll(list_sell.length, true);
                this.hasFirstRender = true;

                // 为了卖盘切换时，流畅的动画
                window.setTimeout(() => {
                    this._addSellBoxAnimate();
                }, 0);
            } else {
                this._setSellScroll(list_sell.length, false);
            }

            // ===================================================================================================
            this.list_buy_disp = this._compose(list_buy, this.oldListBuy,'buy',(curArr)=>{
                this.list_buy = curArr;
            });
            this.list_sell_disp = this._compose(list_sell, this.oldListSell,'sell', (curArr)=>{
                this.list_sell = curArr;
            });

            setTimeout(()=>{
                this.list_buy_disp.forEach((item,index)=>{
                    item.isAdd = false;
                });
                this.list_sell_disp.forEach((item,index)=>{
                    item.isAdd = false;
                });
            },1000)

            // ==============
            // this.list_buy_disp = list_buy;
            // this.list_sell_disp = list_sell;
            // ===================================================================================================


            function setPriceText(list, no, type) {
                let lastItem;
                $.map(list, (item, index) => {
                    if (index === 0) {
                        item.priceText = util.getHighPriceText(item.price, type);
                    } else {
                        if (util.isDiffPrice(lastItem.price, item.price, no) === true) {
                            item.priceText = util.getHighPriceText(item.price, type);
                        } else {
                            item.priceText = util.getLowPriceText(item.price, no, type);
                        }
                    }
                    lastItem = item;
                });
            }
        },

        /**
         * 最近相依信息轮训查询
         * @private
         */
        _loopTrade() {
            commonService.onLoopTradeGetList((rep) => {
            // ===================================================================================================

                 // 请求前  上次的新数组做为老数组
                this.oldListBuy = this.list_buy;   
                this.oldListSell = this.list_sell;
            // ===================================================================================================
            
                this._doResult(rep);
            },{
                symbol:this.wsSymbol
            });
        },

        _loopTradeOnce() {
            commonService.loopTradeGetList({
                symbol: this.wsSymbol
            }).done(rep => {
                this._doResult(rep, true);
            });
        },

        _loopInfo () {
            commonService.onLoopTradeInfo((rep) => {
                this.isLoading = false;
                if(rep === 'nil'){
                    return;
                }
                if (rep['order']) {
                    this.currentPrice = filter.floorFixPrice(rep['order'][0].price,this.$$coinPrecision);
                    if (rep['order'][1]) {
                        this.lastPrice = filter.floorFixPrice(rep['order'][1].price,this.$$coinPrecision);
                    }
                }
            },{
                symbol:this.wsSymbol
            })
        },

        setPanType(currentType) {
            this.panType = currentType;

            let $dom = $(this.$refs.contentBox);
            if (this.panType === PAN_TYPE_NORMAL) {
                this._setPanHeight();

                $dom.removeClass('content-box--buy')
                    .removeClass('content-box--sell');
            } else if (this.panType === PAN_TYPE_BUY) {
                this._setPanHeight();

                $dom.removeClass('content-box--sell')
                    .addClass('content-box--buy');
            } else if (this.panType === PAN_TYPE_SELL) {
                this._setPanHeight();

                $dom.removeClass('content-box--buy')
                    .addClass('content-box--sell');
            }

        },

        /**
         * 设置价格
         * @param price
         * @param amount
         */
        setPrice(price, amount) {
            $(document).trigger('$$market.SetPrice', [price, amount]);
        }

    }
});